package com.xs.anxingo.server.logbak;

import org.apache.commons.lang3.StringUtils;

import java.util.UUID;

/**
 * 重写LogBack线程号
 */
public class LogBackThreadLocal {

    private static final ThreadLocal<String> THREAD_LOCAL_CONTEXT = new ThreadLocal<>();

    /**
     * get local thread context
     *
     * @return
     */
    public static String getCurrentContext() {
        try {
            String context = THREAD_LOCAL_CONTEXT.get();
            if (StringUtils.isBlank(context)) {
                context = getUuidWithTime();
                THREAD_LOCAL_CONTEXT.set(context);
            }
            return context;
        } catch (Exception e) {
            return getUuidWithTime();
        }
    }

    /**
     * init thread local context
     */
    public static void initCurrentContext() {
        try {
            String context;
            if (StringUtils.isNotBlank(THREAD_LOCAL_CONTEXT.get())) {
                removeCurrentContext();
            }
            context = getUuidWithTime();
            THREAD_LOCAL_CONTEXT.set(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * remove thread local context
     */
    public static void removeCurrentContext() {
        String context = THREAD_LOCAL_CONTEXT.get();
        try {
            if (StringUtils.isNotBlank(context)) {
                THREAD_LOCAL_CONTEXT.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 防止uuid重复，增加系统时间，减少重复概率
     * @return
     */
    private static String getUuidWithTime() {
        String str = UUID.randomUUID().toString();
        return System.currentTimeMillis() + "-" + str;
    }
}